package com.iflytek.ci.cpms.controller;

import com.iflytek.ci.cpms.domain.Milestone;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.cpms.service.MilestoneService;
import com.iflytek.ci.cpms.service.ProjectService;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.framework.web.messages.AjaxMessage;
import com.iflytek.ci.cums.service.AccountService;
import com.iflytek.ci.cums.service.impl.ShiroDbRealm;
import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.main.dto.Prior;
import com.iflytek.ci.qams.domain.Issue;
import com.iflytek.ci.qams.domain.IssueInformation;
import com.iflytek.ci.qams.domain.Priopity;
import com.iflytek.ci.qams.domain.SelectCondition;
import com.iflytek.ci.qams.service.IssueService;
import com.iflytek.ci.qams.service.LabelService;
import com.iflytek.ci.qams.service.PriopityService;
import com.iflytek.ci.qams.service.TypeService;
import com.iflytek.framework.mapper.JsonMapper;
import com.iflytek.framework.web.mvc.PaginationParam;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 项目中  反馈信息  维护管理控制器.
 * </p>
 *
 * @author xzyan
 * @version 1.0 2012-12-27 5:10 PM
 * @since JDK 1.5
 */
@Controller
@RequestMapping("project/issue/**")
public class ProjectIssueController extends BaseController{

	/** 序列化ID */
	private static final long serialVersionUID = -6671292143724773032L;
	/**反馈类型服务*/
    @Autowired
    private TypeService typeService;
    /**反馈优先级服务*/
    @Autowired
    private PriopityService priopityService;
     /**反馈标签服务*/
    @Autowired
    private  LabelService labelService;
    /**项目服务*/
    @Autowired
    private ProjectService projectService;
    /**反馈服务*/
    @Autowired
    private IssueService issueService;
    /**用户服务*/
    @Autowired
    private AccountService accountService;

    /**里程碑服务*/
    @Autowired
    private MilestoneService milestoneService;

    /**
     * 跳转到project issue 列表
     * @return  project issue list界面
     */
    @RequestMapping(value = "list/{code}",method = RequestMethod.GET)
    public String p_issue(@PathVariable("code") String code,Model model){
        model.addAttribute("type_json", JsonMapper.nonDefaultMapper().toJson(typeService.all_types()));
        final List<Priopity> priopity_list = priopityService.priopity();
        model.addAttribute("labels", labelService.all_labels());
        model.addAttribute("priopities", priopity_list);
        model.addAttribute("priopities_json", JsonMapper.nonDefaultMapper().toJson(priopity_list));
//        Project project=null;
//    	if(projectId==0){
//    		project=new Project();
//    	} else {
//    		project = projectService.fromId(projectId);
//    	}
        Project project = projectService.fromKey(code);
        model.addAttribute("project",project);
        model.addAttribute("milestone_id",0);
        return "project/issue/list";
    }

    /**
     *    分页获取反馈信息
     *
     * @param criteria  分页参数信息
     * @param tab_id     tab标签：可能值有todo（待处理）  done（已处理）    all（所有(null)）（这前三者为 指派给我的+我负责的，第四个为我提出的）    my_issue (我的反馈)
     * @param p_id    项目id
     * @param m_id    里程碑id
     * @param b_assign    toolbar 右按钮:可能值有:all_my_issue    assign_to_me （指派给我的反馈）
     * @param fix 问题修复开关，可能值有：fixed （已修复 待处理）        f_all（所有 ）
     * @return   反馈信息
     */
    @RequestMapping("list.json")
    @ResponseBody
    public PaginationResult<Issue> pid_issues(
            @PaginationParam(required = true) PaginationCriteria criteria,
            @RequestParam(value = "tab_id", required = false) String tab_id,
            @RequestParam(value = "p_id", required = false) long p_id,
            @RequestParam(value = "m_id", required = false) long m_id,
            @RequestParam(value = "b_assign", required = false) String b_assign,
            @RequestParam(value = "fix", required = false) String fix) {


        SelectCondition selectCondition=new SelectCondition();
        if(StringUtils.equals(fix, "fixed")){
    		selectCondition.setIssuestatus(2);
    	}
        selectCondition.setTab(tab_id);
        selectCondition.setProject(p_id);
        selectCondition.setMilestone(m_id);
        selectCondition.setAssignee(b_assign);
        
        selectCondition.setCriteria(criteria);
        if(tab_id.equals("my_issue")){
        	return issueService.page_by_pro_mile(p_id, m_id, criteria);
        }else{
        	 return issueService.page_issue_by_conditions(selectCondition) ;
        }
    }
    /**
     *  查看问题界面
     *
     * @param issue_key    问题的key
     * @param projectId    项目的id
     * @param model
     * @return   详细问题界面
     */
    @RequestMapping(value = "/view/{issue_key}/{p_id}")
    public String issue_view(@PathVariable String issue_key,@PathVariable("p_id") long projectId, Model model) {
        final IssueInformation issue = issueService.from_key(issue_key);
        model.addAttribute("info", issue);
        List<Priopity> priopity_list = priopityService.priopity();
        model.addAttribute("priopities", priopity_list);
        model.addAttribute("pid",projectId);
        model.addAttribute("project",projectService.fromId(projectId));
        model.addAttribute("labels", labelService.all_labels());
        return "project/issue/view";
    }

    /**
     *   添加问题反馈
     *
     * @param model
     * @param code    项目的key
     * @return    添加问题视图
     */
    @RequestMapping(value = "add/{code}", method = RequestMethod.GET)
    public String add_issue(Model model,@PathVariable(value="code")String code) {
        model.addAttribute("types", typeService.all_types());
        ShiroDbRealm.ShiroUser current_login_usr = (ShiroDbRealm.ShiroUser) SecurityUtils
                .getSubject().getPrincipal();
        // 从数据库中获取当前用户的信息
        final Account account = accountService
                .fromId(current_login_usr.getId());
        Project project=projectService.fromKey(code);
        model.addAttribute("account", account);
        model.addAttribute("project",project);
        logger.info(account.getMail());
        return "project/issue/add";
    }

    /**
     * 根据pid得到这个项目的所有里程碑
     *
     * @param pid    项目id
     * @return    里程碑列表
     */
    @RequestMapping(value = "get_project_milestones/{pid}", method = RequestMethod.GET)
    @ResponseBody
    public  List<Milestone>get_milestones_with_pid(@PathVariable int pid){
        return milestoneService.get_milestones_project(pid);
    }

    @RequestMapping(value = "set_milestones", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage set_milestones_with_pid(
            @RequestParam(value = "issue_id", required = true) String issue_id,
            @RequestParam(value="milestone",required = true) String milestone_id){
        String [] ids=issue_id.split(Prior.SEPARATE);
        issueService.update_issue_milestone(ids,milestone_id);
        return ajax_info("设置成功");
    }
}
